﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Text.Unicode;

namespace BJoin.Common
{
    public static class JsonExtension
    {
        private static readonly JsonSerializerOptions _options;
        static JsonExtension()
        {
            _options = new JsonSerializerOptions
            {
                Encoder = JavaScriptEncoder.Create(UnicodeRanges.All),
            IgnoreNullValues = true,//clean null value field
            PropertyNamingPolicy = JsonNamingPolicy.CamelCase
            };
            _options.Converters.Add(new JsonStringEnumConverter());
        }
        public static string TrySerialize<T>(this T value)
        {
            try
            {
                return JsonSerializer.Serialize(value, _options);
            }
            catch (Exception)
            {
                return string.Empty;
            }
        }

        public static T TryDeserialize<T>(this string data)
        {
            try
            {
                return JsonSerializer.Deserialize<T>(data);
            }
            catch
            {
                return default(T);
            }
        }
    }
}
